<template>
  <div class="common-container px_8">
    <el-breadcrumb separator="/" class="pt_8 pb_16">
      <el-breadcrumb-item @click="handleBack">数据集</el-breadcrumb-item>
      <el-breadcrumb-item>API</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form :inline="true" :label-width="80" label-placement="left" :model="query" size="small">
      <el-form-item label="名称:" prop="name">
        <el-input placeholder="请输入API名称" v-model.trim="query.name" @keyup.enter.native="getMyAPIList" clearable @change="getMyAPIList" />
      </el-form-item>
      <el-form-item label="请求类型:" prop="methods">
        <el-input placeholder="请输入请求类型" v-model.trim="query.methods" clearable @change="getMyAPIList" />
      </el-form-item>
      <el-form-item label="请求地址" prop="server">
        <el-input placeholder="请输入请求地址" v-model.trim="query.server" @keyup.enter.native="getMyAPIList" clearable @change="getMyAPIList" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input placeholder="请输入备注" v-model.trim="query.remark" @keyup.enter.native="getMyAPIList" clearable @change="getMyAPIList" />
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="getMyAPIList">
          <el-icon style="vertical-align: middle;">
            <Search></Search>
          </el-icon>
          <span style="vertical-align: middle;">查询</span>
        </el-button>
        <el-button type="success" @click="handleModalAddAction">
          <el-icon style="vertical-align: middle;">
            <CirclePlus></CirclePlus>
          </el-icon>
          <span style="vertical-align: middle;">新增</span>
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="apiList" border class="w_100" v-loading="apiLoading">
      <el-table-column type="index" width="50" label="序号" align="center" />
      <el-table-column property="name" align="center" label="名称" />
      <el-table-column align="center" property="server" label="请求地址" />
      <el-table-column property="methods" align="center" label="请求类型">
        <template #default="scope">
          <el-tag effect="dark" size="small" :type="showType(scope.row.methods)">{{ scope.row.methods }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" property="remark" label="备注" />
      <el-table-column align="center" property="create_timestamp" label="创建时间">
        <template #default="scope">
          <span>{{ formatTime(scope.row.create_timestamp) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="small" type="success" @click="handleModalEditAction(scope.row)">更新</el-button>
          <el-button size="small" type="danger" @click="handleModalDelAction(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="mt_16 right" v-model:currentPage="query.size" :page-size="query.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange"></el-pagination>
    <el-drawer v-model="APIOpModel" :title="modalTitle[modalStatus]" size="28%" direction="rtl">
      <el-form :model="apiForm" :rules="rules" ref="apiFormRef" label-placement="left" label-width="120px" size="small">
        <el-form-item label="名称:" prop="name">
          <el-input placeholder="请输入名称" v-model.trim="apiForm.name" clearable @change="handleFormChange" />
        </el-form-item>
        <el-form-item label="请求地址:" prop="server">
          <el-input placeholder="请输入请求地址" v-model.trim="apiForm.server" clearable @change="handleFormChange" />
        </el-form-item>
        <el-form-item label="请求类型:" prop="methods">
          <el-select placeholder="请选择请求类型" v-model="apiForm.methods" @change="handleFormChange" clearable filterable>
            <el-option v-for="item in requestMethodsList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input placeholder="请输入备注" type="textarea" clearable v-model.trim="apiForm.remark" />
        </el-form-item>
        <el-tabs v-model="tabName" type="card">
          <el-tab-pane label="Params" name="Params">
            <table class="add_table w_100">
              <tr>
                <th class="pt_6 pb_6" width="70">
                  <span class="iconfont icon-Add cursor_point" @click="addParams"></span>
                </th>
                <th class="pt_6 pb_6">key</th>
                <th class="pt_6 pb_6">value</th>
              </tr>
              <tr v-for="(item,index) in apiForm.Params" :key="index">
                <td width="70" align="center">
                  <span class="iconfont icon-Add cursor_point" @click="addParams(index)"></span>
                  <span class="iconfont icon-close cursor_point pl_2" @click="delParams(index)"></span>
                </td>
                <td>
                  <el-input v-model.trim="item.key" :key="index" clearable></el-input>
                </td>
                <td>
                  <el-input v-model.trim="item.value" :key="index" clearable></el-input>
                </td>
              </tr>
            </table>
          </el-tab-pane>
          <el-tab-pane label="Headers" name="Headers">
            <table class="add_table w_100">
              <tr>
                <th class="pt_6 pb_6" width="70">
                  <span class="iconfont icon-Add cursor_point" @click="addHeaders"></span>
                </th>
                <th class="pt_6 pb_6">key</th>
                <th class="pt_6 pb_6">value</th>
              </tr>
              <tr v-for="(item,index) in apiForm.Headers" :key="index">
                <td width="70" align="center">
                  <span class="iconfont icon-Add cursor_point" @click="addHeaders(index)"></span>
                  <span class="iconfont icon-close cursor_point pl_2" @click="delHeaders(index)"></span>
                </td>
                <td>
                  <el-input v-model.trim="item.key" :key="index" clearable></el-input>
                </td>
                <td>
                  <el-input v-model.trim="item.value" :key="index" clearable></el-input>
                </td>
              </tr>
            </table>
          </el-tab-pane>
          <el-tab-pane label="Body" name="Body">
            <table class="add_table w_100">
              <tr>
                <th class="pt_6 pb_6" width="70">
                  <span class="iconfont icon-Add cursor_point" @click="addBody"></span>
                </th>
                <th class="pt_6 pb_6">key</th>
                <th class="pt_6 pb_6">value</th>
              </tr>
              <tr v-for="(item,index) in apiForm.Body" :key="index">
                <td width="70" align="center">
                  <span class="iconfont icon-Add cursor_point" @click="addBody(index)"></span>
                  <span class="iconfont icon-close cursor_point pl_2" @click="delBody(index)"></span>
                </td>
                <td>
                  <el-input v-model.trim="item.key" :key="index" clearable></el-input>
                </td>
                <td>
                  <el-input v-model.trim="item.value" :key="index" clearable></el-input>
                </td>
              </tr>
            </table>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div class="footer-modal fixed bottom_0 p_8 text_right right_0">
        <el-button @click="handleCloseModal" size="small" class="cursor_point">取消</el-button>
        <el-button type="primary" size="small" class="cursor_point" v-loading="formLoading" @click="handleTestAPI">测试
        </el-button>
        <el-button v-if="modalStatus ==='add'" type="primary" size="small" v-loading="formLoading" class="cursor_point" :disabled="!submitFlag"
          @click="handleAddAPI">确认
        </el-button>
        <el-button v-if="modalStatus ==='edit'" type="primary" size="small" v-loading="formLoading" class="cursor_point" :disabled="!submitFlag"
          @click="handleEditAPI">更新
        </el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="checkModal" title="测试结果" width="50%" destroy-on-close>
      <my-monaco-editor language="json" :height="500" :code="requestData" :auto-format="true"></my-monaco-editor>
      <template #footer>
        <el-button @click="handleCloseModal" plain size="small" class="cursor_point">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { defineComponent, onMounted, ref } from "vue";
import {
  addDataAPI,
  delDataAPI,
  editDataAPI,
  getDataAPIList,
  apiExec,
} from "../../../service/data_api";
import { useRouter } from "vue-router";
import {
  authTypeList,
  requestMethodsList,
  sqlTypeList,
} from "../../../utils/dict";
import { CirclePlus, Search } from "@element-plus/icons-vue";
import { formatDate } from "../../../utils/utils";

export default defineComponent({
  name: "my-data-api",
  components: {
    // NDynamicInput,
    CirclePlus,
    Search,
  },
  setup() {
    const router = useRouter();
    const apiLoading = ref(false);
    const formLoading = ref(false);
    const apiList = ref([]);
    const APIOpModel = ref(false);
    const modalStatus = ref("add");
    const checkModal = ref(false);
    const tabName = ref("Params");
    const total = ref(0);
    const modalTitle = ref({
      add: "新增API",
      edit: "编辑API",
    });
    const requestData = ref("");
    const query = ref({
      size: 1,
      limit: 10,
      name: "",
      methods: "",
      server: "",
      remark: "",
    });
    const handleSizeChange = (pageSize) => {
      query.value.size = 1;
      query.value.limit = pageSize;
      getMyAPIList();
    };
    const handleCurrentChange = (size) => {
      query.value.size = size;
      getMyAPIList();
    };
    const apiForm = ref({
      name: undefined,
      remark: undefined,
      server: undefined,
      methods: undefined,
      Params: [],
      Headers: [{ key: "Content-Type", value: "application/json" }],
      Body: [],
    });
    const apiFormRef = ref(null);
    const submitFlag = ref(false);
    const handleFormChange = () => {
      submitFlag.value = false;
    };
    const resetForm = () => {
      apiForm.value = {
        name: undefined,
        remark: undefined,
        server: undefined,
        methods: undefined,
        Params: [],
        Headers: [{ key: "Content-Type", value: "application/json" }],
        Body: [],
      };
    };
    const handleModalAddAction = () => {
      resetForm();
      modalStatus.value = "add";
      APIOpModel.value = true;
    };
    const handleCloseModal = () => {
      APIOpModel.value = false;
    };
    const getMyAPIList = () => {
      apiLoading.value = true;
      getDataAPIList(query.value)
        .then((res) => {
          apiList.value = res.data.result;
          apiLoading.value = false;
          total.value = res.data.total;
        })
        .catch(() => {
          apiLoading.value = false;
        });
    };
    const handleTestAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          apiExec(apiForm.value)
            .then((res) => {
              formLoading.value = false;
              ElMessage({
                type: "success",
                message: "连接API成功",
              });
              checkModal.value = true;
              submitFlag.value = true;
              requestData.value = JSON.stringify(res);
            })
            .catch((err) => {
              formLoading.value = false;
              ElMessage.error("连接API失败");
            });
        }
      });
    };
    const handleAddAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, apiForm.value, {
            Params: JSON.stringify(apiForm.value.Params),
            Headers: JSON.stringify(apiForm.value.Headers),
            Body: JSON.stringify(apiForm.value.Body),
          });
          addDataAPI(data)
            .then(() => {
              ElMessage({
                type: "success",
                message: "新增API成功",
              });
              formLoading.value = false;
              handleCloseModal();
              getMyAPIList();
            })
            .catch((err) => {
              formLoading.value = false;
              ElMessage.error("新增API失败");
            });
        }
      });
    };
    const handleModalEditAction = (rowData) => {
      resetForm();
      apiForm.value = Object.assign({}, rowData, {
        Params: JSON.parse(rowData.Params),
        Headers: JSON.parse(rowData.Headers),
        Body: JSON.parse(rowData.Body),
      });
      modalStatus.value = "edit";
      submitFlag.value = false;
      APIOpModel.value = true;
    };
    const handleEditAPI = () => {
      formLoading.value = true;
      apiFormRef.value.validate((valid) => {
        if (valid) {
          let data = Object.assign({}, apiForm.value, {
            Params: JSON.stringify(apiForm.value.Params),
            Headers: JSON.stringify(apiForm.value.Headers),
            Body: JSON.stringify(apiForm.value.Body),
          });
          editDataAPI(data)
            .then(() => {
              ElMessage({
                type: "success",
                message: "编辑API成功",
              });
              handleCloseModal();
              getMyAPIList();
              formLoading.value = false;
            })
            .catch((err) => {
              formLoading.value = false;
              ElMessage.success("编辑API失败");
            });
        } else {
          formLoading.value = false;
        }
      });
    };
    const handleModalDelAction = (rowData) => {
      ElMessageBox.confirm(`你确定删除 ${rowData.name} 么？`, "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        handleDelAPI(rowData);
      });
    };
    const handleDelAPI = (rowData) => {
      delDataAPI({ data_api_id: rowData.data_api_id })
        .then(() => {
          ElMessage({
            type: "success",
            message: "删除API成功",
          });
          getMyAPIList();
        })
        .catch(() => {
          ElMessage.error("删除API失败");
        });
    };
    const handleBack = () => {
      router.push({ path: "index" });
    };
    const handleCheckCloseModal = () => {
      checkModal.value = false;
    };
    const showType = (type) => {
      let tagType;
      switch (type) {
        case "POST":
          tagType = "success";
          break;
        case "GET":
          tagType = "";
          break;
        case "PUT":
          tagType = "info";
          break;
        case "DELETE":
          tagType = "warning";
          break;
        default:
          break;
      }
      return tagType;
    };
    const addParams = (index) => {
      let paramsArr = [...apiForm.value.Params];
      if (typeof index === "number") {
        apiForm.value.Params = [
          ...paramsArr.splice(0, index + 1),
          {
            key: "",
            value: "",
          },
          ...paramsArr.splice(index - 1, paramsArr.length),
        ];
      } else {
        apiForm.value.Params.push({
          key: "",
          value: "",
        });
      }
    };
    const delParams = (index) => {
      apiForm.value.Params.splice(index, 1);
    };
    const addHeaders = (index) => {
      let headersArr = [...apiForm.value.Headers];
      if (typeof index === "number") {
        apiForm.value.Headers = [
          ...headersArr.splice(0, index + 1),
          {
            key: "",
            value: "",
          },
          ...headersArr.splice(index - 1, headersArr.length),
        ];
      } else {
        apiForm.value.Headers.push({
          key: "",
          value: "",
        });
      }
    };
    const delHeaders = (index) => {
      apiForm.value.Headers.splice(index, 1);
    };
    const addBody = (index) => {
      let BodyArr = [...apiForm.value.Body];
      if (typeof index === "number") {
        apiForm.value.Body = [
          ...BodyArr.splice(0, index + 1),
          {
            key: "",
            value: "",
          },
          ...BodyArr.splice(index - 1, BodyArr.length),
        ];
      } else {
        apiForm.value.Body.push({
          key: "",
          value: "",
        });
      }
    };
    const delBody = (index) => {
      apiForm.value.Body.splice(index, 1);
    };
    const formatTime = (num) => {
      return formatDate(num, "yyyy-MM-dd hh:mm:ss");
    };
    onMounted(() => {
      getMyAPIList();
    });
    return {
      rules: {
        name: {
          required: true,
          trigger: ["blur", "input"],
          message: "请输入API名称",
        },
        methods: {
          required: true,
          message: "请选择API类型",
          trigger: ["change"],
        },
        server: {
          required: true,
          message: "请输入服务器地址",
          trigger: ["input", "blur"],
        },
      },
      query,
      total,
      tabName,
      checkModal,
      apiList,
      APIOpModel,
      apiForm,
      submitFlag,
      apiFormRef,
      modalStatus,
      modalTitle,
      requestData,
      apiLoading,
      formLoading,
      authTypeList,
      requestMethodsList,
      sqlTypeList: sqlTypeList,
      formatTime,
      addParams,
      delParams,
      addHeaders,
      delHeaders,
      addBody,
      delBody,
      handleSizeChange,
      handleCurrentChange,
      getMyAPIList,
      handleCloseModal,
      handleModalAddAction,
      handleFormChange,
      resetForm,
      handleDelAPI,
      handleModalDelAction,
      handleModalEditAction,
      handleTestAPI,
      handleAddAPI,
      handleEditAPI,
      handleBack,
      handleCheckCloseModal,
      showType,
    };
  },
});
</script>

